package cn.edu.xmu.tangzk.scala.byexs

import scala.annotation.tailrec

/**
 * 求oper(f(a), ..., f(b))的值
 */
object Ex05_2_4 {

    def factOper(oper: (Int, Int) => Int)(f: Int => Int)(a: Int, b: Int, one: Int): Int = {
        @tailrec def factOperIter(a: Int, result: Int): Int = {
            if (a > b) result
            else { factOperIter(a + 1, oper(f(a), result)) }
        }
        factOperIter(a, one)
    }

    def main(args: Array[String]) {
        val result0 = factOper(_ + _)(x => 2 * x)(2, 4, 0)
        assert(result0 == 18)
        val result1 = factOper(_ * _)(x => x)(2, 4, 1)
        assert(result1 == 24)
        println(result0, result1)
    }

}